﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using Application = Autodesk.Revit.ApplicationServices.Application;
using xXYZ = Autodesk.Revit.DB.XYZ;

namespace RevitAddin
{
    [TransactionAttribute(TransactionMode.Manual)]
    [RegenerationAttribute(RegenerationOption.Manual)]
    public class YLCCodeCMD : IExternalEventHandler
    {

        public Action<List<XYZ>> action { get; set; }
        public int count { get; set; }

        public void Execute(UIApplication app)
        {
            UIDocument uidoc = app.ActiveUIDocument;
            Document doc = uidoc.Document;
            Application revitApp = app.Application;



            int index = 0;
            try
            {
                List<xXYZ> xyzList = new List<xXYZ>();
                
                while (index < count)
                {

                    Reference refer = uidoc.Selection.PickObject(ObjectType.Edge, "请按照顺序选择预留槽边");
                    Element elem = doc.GetElement(refer);
                    Edge edge = elem.GetGeometryObjectFromReference(refer) as Edge;
                    Curve curve = edge.AsCurve() as Curve;

                    List<xXYZ> points = curve.Tessellate().ToList();
                    List<xXYZ> tempPoints = new List<xXYZ>();
                    Arc arc = curve as Arc;
                    if (arc != null)
                    {
                        for (int i = 0; i < points.Count; i += 3) tempPoints.Add(points[i]);
                    }
                    else
                    {
                        for (int i = 0; i < points.Count; i += 1) tempPoints.Add(points[i]);
                    }

                    xyzList = xyzList.Concat(tempPoints).ToList();
                    if (index == count - 1)
                    {
                        xyzList.Add(curve.Evaluate(1, true));
                    }
                    index++;
                }
                List<XYZ> myList = comMethod.xXYZ2XYZ(xyzList).OrderBy(x => x.X).ToList();

                #region 写入文件
                // 将点列表转换为对象列表（带 X, Y, Z）
                List<object> formattedList = new List<object>();
                foreach (var point in myList)
                {
                    formattedList.Add(new { X = point.X, Y = point.Y, Z = point.Z });
                }

                // 将对象列表序列化为 JSON 字符串
                string jsonString = JsonConvert.SerializeObject(formattedList);

                // 定义输出文件路径
                string filePath = @"C:\Temp\output.txt";  // 请根据需要修改路径

                try
                {
                    // 使用 StreamWriter 将 JSON 字符串写入文件
                    using (StreamWriter writer = new StreamWriter(filePath))
                    {
                        writer.WriteLine("\"YLCxyzList\": " + jsonString);
                    }

                    // 提示用户写入成功
                    Console.WriteLine("JSON 已成功写入到 " + filePath);
                }
                catch (Exception ex)
                {
                    // 捕获并显示可能的异常
                    Console.WriteLine("写入文件时发生错误: " + ex.Message);
                }
                #endregion

                action?.Invoke(myList);

            }
            catch (Exception ex)
            {
                TaskDialog.Show("温馨提示1", "\n" + ex.Message + ex.StackTrace);
            }
        }

        public string GetName()
        {
            return "YLCCodeCMD";
        }
    }

}
